const Router = require('@koa/router')
const mongoose = require('mongoose')

const Todo = mongoose.model('Todo')

const router = new Router({
    prefix: '/todo'
})
// /todo/add
router.post('/add', async (ctx) => {
    let {
        userId,
        content,
        state //待办默认0
    } = ctx.request.body
    const todo = new Todo({
        userId,
        content,
        state
    })
    const res = await todo.save()
    ctx.body = {
        data: res,
        code: 200,
        msg: '添加待办成功'
    }
})
//更新
router.post('/update', async (ctx) => {
    const {
        id,
        state
    } = ctx.request.body
    console.log(`id,state`, id, state);
    //更新_id为id的记录为state新值
    const res = await Todo.update(
        {
            "_id": id
        },
        { $set: { "state": state } }
    )
    ctx.body = {
        data: res,
        msg: '修改状态成功',
        code: 200
    }
})
router.delete('/:id', async (ctx) => {
    const {
        id
    } = ctx.params
    const res = await Todo.deleteOne({
        _id: id
    })
    ctx.body = {
        code: 200,
        msg: '删除成功',
        data: res
    }
})
// 0 1 2  3全部
router.post('/list', async (ctx) => {
    let {
        userId,
        type
    } = ctx.request.body
    //全部
    if (type == 3) {
        const list = await Todo.find({ userId: userId }).sort({ _id: -1 }).exec()
        const total = await Todo.countDocuments().exec()
        ctx.body = {
            data: {
                list,
                total
            },
            code: 200,
            msg: '获取全部列表成功'
        }
    }
    //待办
    if (type == 0) {
        const list = await Todo.find({
            state: 0,
            userId: userId
        }).sort({ _id: -1 }).exec()
        const total = await Todo.countDocuments().exec()
        ctx.body = {
            data: {
                list,
                total
            },
            code: 200,
            msg: '获取待办列表成功'
        }
    }
    //在做
    if (type == 1) {
        const list = await Todo.find({
            state: 1,
            userId: userId
        }).sort({ _id: -1 }).exec()
        const total = await Todo.countDocuments().exec()
        ctx.body = {
            data: {
                list,
                total
            },
            code: 200,
            msg: '获取在做列表成功'
        }
    }
    //在做
    if (type == 2) {
        const list = await Todo.find({
            state: 2,
            userId: userId
        }).sort({ _id: -1 }).exec()
        const total = await Todo.countDocuments().exec()
        ctx.body = {
            data: {
                list,
                total
            },
            code: 200,
            msg: '获取已完成列表成功'
        }
    }

})

module.exports = router